import express from 'express'
import { listSql, likeSql, getResult, addSql, detailSql, putSql, deleteSql, countSql, multiDeleteSql } from '../../../util/operateSql.js';
import { arrayToTree } from '../../../util/common.js';
import { getAccount, getPlatform, isExistUser } from '../../../middleWare/user/index.js';

var router = express.Router();
const TABLE1 = 'activity_master.t_category'
const TABLE2 = 'activity_master.t_spu'
const TABLE3 = 'activity_master.t_sku'

/**
 * 
 * @param {Array} arr 需要遍历的数组
 * @returns {boolean} 是否是最后一个层级 
 */
const isEndLevel = (arr) => {
  return arr.every(e => {
    return !e.if_parent
  })
}

const getFirstLevel = async () => {
  const sql = likeSql(TABLE1, {parent_id: null}, '=')
  
  const rows = await getResult(sql)
  
  return Promise.resolve(rows)
}

const getValidateCategory = async (merchant_id) => {
  const sql = listSql(TABLE1,{is_show:1,orderBy:'sort',sort:'asc',merchant_id},{hasPage: false})
  
  const rows = await getResult(sql)
  return Promise.resolve(rows)
}

const getAllCategory = async (merchant_id) => {
  const sql = listSql(TABLE1,{orderBy:'sort',sort:'asc',merchant_id},{hasPage: false})
  const rows = await getResult(sql)
  return Promise.resolve(rows)
}

const getAllSpuByCategory = async (merchant_id,category_id=null) => {
  const sql = listSql(TABLE2,{merchant_id,category_id,parent_group_code:category_id},{hasPage: true,operate: {'in':['parent_group_code']}})
	console.log('sql: ', sql);
  const rows = await getResult(sql)
  return Promise.resolve(rows)
}

/**
 * 
 * @param {Array<any>} arr 数组对象
 * @param {boolean} condition 判断条件的字段
 * @returns {boolean} 当前层级是否含有子及
 */
const hasChildren = (arr = [],condition) => {
  if (!Array.isArray(arr) || arr.length <= 0) return false
  return arr.some(item => {
    return !!item[condition]
  })
}


/**
 * 
 * @param {array} datas 遍历获取子层级 
 * @returns 树形结构数据
 */
const fn = async (merchant_id=undefined,showAll=false) => {
  let allData;
  try {
		// datas = await getFirstLevel()
		showAll
    ?allData = await getAllCategory(merchant_id)
    :allData = await getValidateCategory(merchant_id)
    
    return Promise.resolve(allData)
    
  } catch (error) {
    return Promise.reject(error)
  }
}


/**
 * 多层级分类list
*/
router.post('/categories/list',getAccount,getPlatform, async (req, res, next) => {
  try {
    let rows;
    if (req.platform == 'applet') {
      
      const {merchant_id} = req.headers
      rows = await fn(merchant_id)
      rows = rows.filter(e => {
        return e.merchant_id == merchant_id
      })
    } else if (req.platform == 'pc') {
      const {id:merchant_id} = req.master 
      rows = await fn(merchant_id)
      rows = rows.filter(e => {
        return e.merchant_id == req.master.id
      })
    }
    res.json(req.app.locals.success(rows))
  } catch (error) {
    
    res.json(req.app.locals.error(error.message))
  }
  
})
/**
 * 多层级分类tree
*/
router.post('/categories/tree',getPlatform,getAccount, async (req, res, next) => {
  const {isAll=false} = req.body 
  try {
    let rows;
    if (req.platform == 'applet') {
      const {merchant_id} = req.headers
      rows = await fn(merchant_id,isAll)
      rows = rows.filter(e => {
        return e.merchant_id == merchant_id
      })
    } else if (req.platform == 'pc') {
      const {id:merchant_id} = req.master 
      rows = await fn(merchant_id,isAll)
      rows = rows.filter(e => {
        return e.merchant_id == req.master.id
      })
    }
    res.json(req.app.locals.success(arrayToTree(rows)))
  } catch (error) {
    
    res.json(req.app.locals.error(error.message))
  }
  
})

/**
 * spu分类列表新增
*/
router.post('/categories/add',getAccount, async (req, res, next) => {
  try {
    let {name,parent_id=null,sort=0} = req.body,if_parent = 1,is_show=1
    let parent_group_code=null
    if (parent_id) {
      const rows =await getResult(detailSql(TABLE1,{id:parent_id}))
      parent_group_code = rows[0].parent_group_code ? `${rows[0].parent_group_code},${parent_id}` : parent_id
      if (parent_group_code && parent_group_code.toString().split(',').length >= 3) {
        res.json(req.app.locals.error('新增超过层级'))
        return
      }
    }
    const sql = addSql(TABLE1,{name,parent_id,sort:+sort,if_parent,is_show,parent_group_code,merchant_id: req.master.id})
    getResult(sql).then((result) => {
      res.json(req.app.locals.success('新增成功'))
    });
  } catch (error) {
    
    
    res.json(req.app.locals.error(error.message))
  }
  
})

router.post('/categories/update',async (req,res,next) => {
  const {id,name,parent_id,sort} = req.body
	console.log('req.body: ', req.body);
  const sql = putSql(TABLE1,{sort,name,parent_id},{id})
	console.log('putSql: ', sql);
  try {
    await getResult(sql)
    res.json(req.app.locals.success('修改成功'))
  } catch (error) {
    res.json(req.app.locals.error(error.message))
    
  }
  
})
router.post('/categories/hide',async (req,res,next) => {
  const {id,is_show} = req.body
	const hideSql = `update ${TABLE1} set is_show = ${is_show} where LOCATE(${id},parent_group_code) > 0 or id = ${id}`

  try {
    await getResult(hideSql)
    res.json(req.app.locals.success('修改成功'))
  } catch (error) {
    res.json(req.app.locals.error(error.message))
    
  }
  
})
router.post('/categories/delete',async (req,res,next) => {
  const {id} = req.body
  const productsSql = countSql(TABLE2,{category_id: id})
  
  const categoriesSql = countSql(TABLE1,{parent_id: id})
  

  try {
    const resp = await getResult(productsSql)
    
    if (resp[0].count > 0) {
      res.json(req.app.locals.error('分类下存在商品'))
      return
    }
    const resp2 = await getResult(categoriesSql)
    if (resp2[0].count > 0) {
      res.json(req.app.locals.error('有下级分类'))
      return
    }
    const delSql = deleteSql(TABLE1,{id: +id})
    
    const resp3 = await getResult(delSql)
    res.json(req.app.locals.success('删除成功'))
  } catch (error) {
    res.json(req.app.locals.error(error.message))
    
  }
  
})


/**
 * 根据当前分类查spu
 */
router.get('/productsByCateId',async (req,res,next) => {
  const {id=null} = req.query
  const sql = likeSql(TABLE2,{category_id:+id},'=')
  
  const rows = await getResult(sql)
  res.json(req.app.locals.success(rows))

})


/**
 * C端根据当前一级分类id查下层级每个分类spu10条
 */
router.get('/productsByTopLimit',async (req,res,next) => {
  const {merchant_id} = req.headers
  const {id:category_id=null,title='',limit=10} = req.query
 try {
	const getAllCategorySql = `SELECT * FROM ${TABLE1} ${category_id? `WHERE LOCATE(${category_id},parent_group_code) > 0 or id = ${category_id}`: ''}`
	let filterCategoryIds = await getResult(getAllCategorySql)
	filterCategoryIds = filterCategoryIds.map(e => e.id)
	const limitSql = `SELECT * from (SELECT *, ROW_NUMBER() OVER(
		PARTITION BY category_id 
		ORDER BY update_time DESC) as row_num FROM t_spu) t where t.row_num <= ${limit} and category_id in (${filterCategoryIds.join()})`
   const rows = await getResult(limitSql)   
   res.json(req.app.locals.success(rows))
 } catch (error) {
	console.log('error: ', error);

   res.json(req.app.locals.error(error))
 } 

})


/**
 * C端根据当前一级分类id查下层级所有spu
 */
router.get('/productsByTop',async (req,res,next) => {
  const {merchant_id} = req.headers
  const {id:category_id=null,title='',pageSize=20,pageIndex=1} = req.query
    
 try {
	const getAllCategorySql = `SELECT * FROM ${TABLE1} ${category_id? `WHERE LOCATE(${category_id},parent_group_code) > 0 or id = ${category_id}`: ''}`
	let filterCategoryIds = await getResult(getAllCategorySql)
	filterCategoryIds = filterCategoryIds.map(e => e.id)
   const sql = listSql(TABLE2,{title,category_id:filterCategoryIds,merchant_id,pageIndex,pageSize},{linkChar: 'and',operate:{'like':['title'],'in':['category_id']}})
   const sql2 = countSql(TABLE2,{title,category_id:filterCategoryIds,merchant_id,pageIndex,pageSize},{linkChar: 'and',operate:{'like':['title'],'in':['category_id']}})
   const rows = await getResult(sql)
   const countRows = await getResult(sql2)
   
   res.json(req.app.locals.success({list:rows,total: countRows[0].count}))
 } catch (error) {
	console.log('error: ', error);

   res.json(req.app.locals.error(error))
 } 

})

router.get('/spu/query',getAccount,async (req,res,next) => {
  const {category_id,title,pageIndex=1,pageSize=20} = req.query
  
  const {id:merchant_id} = req.master
  
 try {
	const getAllCategorySql = `SELECT * FROM ${TABLE1} ${category_id? `WHERE LOCATE(${category_id},parent_group_code) > 0 or id = ${category_id} and is_show = 1`: ''}`
	let filterCategoryIds = await getResult(getAllCategorySql)
	filterCategoryIds = filterCategoryIds.map(e => e.id)
   const sql = listSql(TABLE2,{...req.query,title,category_id:filterCategoryIds,merchant_id},{linkChar: 'and',operate:{'like':['title'],'in':['category_id']}})
   const sql2 = countSql(TABLE2,{...req.query,title,category_id:filterCategoryIds,merchant_id},{linkChar: 'and',operate:{'like':['title'],'in':['category_id']}})
   const rows = await getResult(sql)
   const countRows = await getResult(sql2)
   
   res.json(req.app.locals.success({list: rows,total: countRows[0].count}))
 } catch (error) {
	console.log('error: ', error);

   res.json(req.app.locals.error(error))
 } 
})

// C端首页unit显示
router.get('/spu/home',getAccount,async (req,res,next) => {
	const {merchant_id} = req.headers

 try {
   const sql = listSql(TABLE2,{...req.query,merchant_id,orderBy: 'update_time'})
	 
   
   const sql2 = countSql(TABLE2,{...req.query,merchant_id,orderBy: 'update_time'})
   const rows = await getResult(sql)
   const countRows = await getResult(sql2)
   
   res.json(req.app.locals.success({list: rows,total: countRows[0].count}))
 } catch (error) {
  
  
   res.json(req.app.locals.error(error))
 } 
})

/**
 * 新增商品
 */
router.post('/spu/add',getAccount,async (req,res,next) => {
  try {
    const {title,sub_title,category_id,brand_id,vipPrice,price} = req.body
    req.body.merchant_id = req.master?.id
    const sql = addSql(TABLE2,req.body)
    const rows = await getResult(sql)
    res.json(req.app.locals.success('新增成功'))
  } catch (error) {
    
    res.json(req.app.locals.error(error))
  }
})
/**
 * 更新商品
 */
router.post('/spu/update',async (req,res,next) => {
  try {
    const {title,sub_title,category_id,brand_id,img_url,rich_text,vipPrice,price,id} = req.body
    const sql = putSql(TABLE2,{title,sub_title,category_id,img_url,rich_text,brand_id,vipPrice,price},{id})
		console.log('sql: ', sql);
    
    const rows = await getResult(sql)
    res.json(req.app.locals.success('修改成功'))
  } catch (error) {
    res.json(req.app.locals.error(error))
  }
})
/**
 * 删除商品
 */
router.post('/spu/delete',async (req,res,next) => {
  try {
    const {ids} = req.body
    const sql = multiDeleteSql(TABLE2,{ids,logic:false})
    const rows = await getResult(sql)
    res.json(req.app.locals.success('删除成功'))
  } catch (error) {
    res.json(req.app.locals.error(error))
  }
})

/**
 * 商品详情
 */
router.get('/spu/detail',async (req,res,next) => {
  try {
    const {id} = req.query
    const sql = detailSql(TABLE2,{id})
    const rows = await getResult(sql)
    const row = rows.length > 0? rows[0] : undefined
    if (row) {
      const sql = listSql(TABLE3,{spu_id:id})
      const skus = await getResult(sql)
      row['skuList'] = skus
    }
    row
    ? res.json(req.app.locals.success(row))
    : res.json(req.app.locals.success({}))
  } catch (error) {
    res.json(req.app.locals.error(error))
  }
})

// 查询sku
// router.get('/skus',async(req, res, next ) => {
//   try {
//     try {
//       const {spu_id} = req.query
//       const sql = detailSql(TABLE3,{spu_id})
//       const rows = await getResult(sql)
//       res.json(req.app.locals.success(rows))
//     } catch (error) {
//       res.json(req.app.locals.error(error))
//     }
//   } catch (error) {
//     res.json(req.app.locals.error(error))
//   }
// })


export default router